package com.cms.controller.front;

import com.cms.Config;
import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.routes.RouteMapping;
import com.cms.util.*;
import com.jfinal.kit.PathKit;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：chenxf
 * @date ：Created in 2020/7/23 15:06
 * @description：
 * @modified By：
 * @version: $
 */
@RouteMapping(url = "/weix")
public class WxController extends BaseController{

    private String appid="wx8d63715e2d5caec7";
    private String secret="d5d96789ab3c0be014ae51b018dcb5fe";

    private String qrUrl="https://hanjiayx.com/weix?crtName=NAME";

    /**
     * 首页
     */
    public void index(){
       // String s= WxUtil.getGZHUrl("wx8d63715e2d5caec7","https://hanjiayx.com/site/");
        // Map m= WxUtil.getOpenIdDetail("wxe82e8e016edc2f0f","28ed49be53cb56abba5077004c0d120d","o_xIE1mpvHMFABHznOF0tadHUfTo");
       // System.out.println("result={}"+s);
      //  this.redirect(WxUtil.getGZHUrl("wx8d63715e2d5caec7","https://hanjiayx.com/site/"));

        render("/templates/"+getTheme()+"/"+getDevice()+"/weix.html");
    }

    public void register(){
        render("/templates/"+getTheme()+"/"+getDevice()+"/register.html");
    }

    public void denlu() {
        String  code = getPara("code");
        renderJson(new ObjectRestResponse().rel(true).result(WxUtil.getOpenId(appid, secret, code)));
    }


    public void code() {
        Member currentMember = getCurrentMember();
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
        String qrCode = this.saveMinaCode(currentMember.getId().toString(), currentMember.getInviteCode());
        if (StringUtils.isBlank(qrCode)) {
            renderJson( new ObjectRestResponse().rel(false).msg("推广码生成失败"));
            return;
        }
        resultMap.put("qrCode", qrCode);
        resultMap.put("crtName",currentMember.getInviteCode());

        renderJson(new ObjectRestResponse().rel(true).msg("查询成功").result(resultMap));

    }

    private String saveMinaCode(String userId, String crtName) {
        Config config = SystemUtils.getConfig();
        String uploadPath = PathKit.getWebRootPath()+"/../upload";


        String webRoot =
                uploadPath + File.separator + "weixin" + File.separator;
        String saveUrl = "/upload/weixin/" + userId + ".jpg";
        File directoryFile = new File(webRoot);
        if (!directoryFile.exists()) {
            directoryFile.mkdirs();
        }
        String codePath = webRoot + userId + ".jpg";
        File codeFile = new File(codePath);
        if (codeFile.exists()) {
            return saveUrl;
        }
       // Path path = Paths.get(webRoot + userId + ".jpg");
        String newWeixinUrl=WxUtil.getGZHUrl(appid, qrUrl.replace("NAME",crtName));

        QRUtil.saveQrCode(codePath, PathKit.getWebRootPath()+config.getLogo(), newWeixinUrl, 300, 300,
                "");

        return saveUrl;
    }

    public void codeLogin() {
        String  unionid = getPara("unionid");
        Member member = new Member().dao().findByOpenId(unionid);
        if(member == null){
           // setAttr("feedback", Feedback.error("用户不存在"));

            renderJson( new ObjectRestResponse().rel(false).result(WxUtil.getOpenIdDetail(appid,secret,unionid)));
            return;

        }

         getSession().setAttribute(Member.SESSION_MEMBER, member);
        renderJson( new ObjectRestResponse().rel(true).msg("登陆成功").result(member));
        return ;

    }

}
